package com.atguigu.lease.web.admin.service.impl;

import com.atguigu.lease.common.minio.MinioProperties;
import com.atguigu.lease.web.admin.service.FileService;
import io.minio.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.UUID;

@Service
public class FileServiceImpl implements FileService {
    @Autowired
    private MinioProperties minioProperties;
    @Autowired
    private MinioClient minioClient;

    @Override
    public String uploadFile(MultipartFile file) throws Exception {
        //1.判断是否有桶
        boolean is = minioClient.bucketExists(BucketExistsArgs.builder().bucket(minioProperties.getBucketName()).build());
        //2.没有创建,并且设置访问权限问题
        if (!is){
            minioClient.makeBucket(MakeBucketArgs.builder().bucket(minioProperties.getBucketName()).build());
            String bucketPolicyConfig = createBucketPolicyConfig(minioProperties.getBucketName());
            minioClient.setBucketPolicy(SetBucketPolicyArgs.builder().bucket(minioProperties.getBucketName()).config(bucketPolicyConfig).build());
        }
        //3.文件上传处理(对象名需要去重处理)
        //3.1 处理下对象名(文件名),文件名重复 | 一天又很多图片呢?
        String objectName =new SimpleDateFormat("yyyyMMdd").format(new Date()) +"/"+ UUID.randomUUID().toString().replaceAll("-","") + '_' + file.getOriginalFilename();
        minioClient.putObject(PutObjectArgs.builder()
                .bucket(minioProperties.getBucketName())
                .object(objectName)
                .stream(file.getInputStream(),file.getSize(),-1)
                .contentType(file.getContentType())
                .build());
        //4.拼接访问地址即可
        String join = String.join("/", minioProperties.getEndpoint(), minioProperties.getBucketName(), objectName);
        System.out.println("join = " + join);
        return join;
    }


    private String createBucketPolicyConfig(String bucketName) {

        return """
            {
              "Statement" : [ {
                "Action" : "s3:GetObject",
                "Effect" : "Allow",
                "Principal" : "*",
                "Resource" : "arn:aws:s3:::%s/*"
              } ],
              "Version" : "2012-10-17"
            }
            """.formatted(bucketName);
    }
}


